package move;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

public class CanvasPanel extends JPanel {

    private static final long serialVersionUID = -465246484602975700L;
    private static final int RADIUS = 5;
    private static final int STEP = 2;

    private Point2D mover;

    public CanvasPanel() {
        setBackground(Color.BLACK);
        setForeground(Color.WHITE);
        mover = new Point2D.Double();
        reset();
    }

    private void drawLine(Graphics2D g2d) {
        g2d.setColor(Color.GREEN);
        Line2D line = new Line2D.Double(0, getY(0), 50, getY(50));
        g2d.draw(line);
    }

    private void drawMover(Graphics2D g2d) {
        g2d.setColor(Color.RED);

        Ellipse2D shape = new Ellipse2D.Double(mover.getX() - RADIUS, mover.getY() - RADIUS, 2 * RADIUS, 2 * RADIUS);
        g2d.fill(shape);
    }

    private double getStepX() {
        return STEP / (Math.sqrt(10 * 10 + 1));
    }

    private double getStepY() {
        return 10 * getStepX();
    }

    private double getY(double x) {
        return 10 * x - 20;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        drawLine((Graphics2D) g);
        drawMover((Graphics2D) g);
    }

    private void reset() {
        mover.setLocation(0, getY(0));
    }

    public void run() {
        // y = 0.5x + 15
        reset();
        new Thread(() -> {
            while (mover.getX() < CanvasPanel.this.getWidth() && mover.getY() < CanvasPanel.this.getHeight()) {
                mover.setLocation(mover.getX() + getStepX(), mover.getY() + getStepY());
                repaint();

                try {
                    Thread.sleep(17);
                } catch (InterruptedException e) {
                    System.err.println(e.getMessage());
                    Thread.currentThread().interrupt();
                }
            }
        }).start();
    }

}
